import os
from PyPDF4 import PdfFileReader
from pathlib import Path


def get_pages_count(file):
    try:
        pdf = PdfFileReader(open(file, 'rb'))
        return pdf.getNumPages()
    except:
        return "无法统计"


def count_dir_pdf_pages(pdf_dir, result_dir):
    os.makedirs(result_dir, exist_ok=True)
    result_file = os.path.join(result_dir, 'pdfpages.txt')
    with open(result_file, "w", encoding='utf-8') as f:
        for path in Path(pdf_dir).rglob('*.pdf'):
            # print(path)
            # print(get_pages_count(path))
            short_path = str(path).replace(pdf_dir, "")
            line = f'{short_path}${get_pages_count(path)}'
            print(line)
            f.write(f'{line}\r\n')
    print(f'wrote pages to {result_file}')


if __name__ == "__main__":
    count_dir_pdf_pages(r'C:\Users\YANG.LEI\Downloads', r'C:\Users\YANG.LEI\Downloads\pages')
